package com.zhy.sunmi.fragment.sell;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
//import androidx.room.util.StringUtil;

import com.hjq.xtoast.XToast;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.greendao.gen.CouponsDao;
import com.zhy.greendao.gen.GoodsCateDao;
import com.zhy.greendao.gen.GoodsDao;
import com.zhy.greendao.gen.SellGoodHistoryDao;
import com.zhy.greendao.gen.SoldGoodDetailDao;
import com.zhy.greendao.gen.UserDao;
import com.zhy.sunmi.MyApplication;
import com.zhy.sunmi.PrintUtil4;
import com.zhy.sunmi.R;
import com.zhy.sunmi.bean.Coupons;
import com.zhy.sunmi.bean.Goods;
import com.zhy.sunmi.bean.GoodsCate;
import com.zhy.sunmi.bean.ProductResultBean;
import com.zhy.sunmi.bean.SellGoodHistory;
import com.zhy.sunmi.bean.SellingGood;
import com.zhy.sunmi.bean.SoldGoodDetail;
import com.zhy.sunmi.bean.User;
import com.zhy.sunmi.utils.ProductResultUtils;
import com.zhy.sunmi.utils.ScreenUtils;
import com.zhy.sunmi.utils.XMathUtil;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.zhy.sunmi.MyApplication.pos_usb;
import static com.zhy.sunmi.utils.PrintUtil.cutPaper;
import static com.zhy.sunmi.utils.PrintUtil.printBar;
import static com.zhy.sunmi.utils.PrintUtil.printText;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SubSellFragment#} factory method to
 * create an instance of this fragment.
 */
public class SubSellFragment extends Fragment {
    /**
     * 左侧商品recyclerView
     */
    private NestedScrollView nestedScrollView;


    /**
     * 左侧商品recyclerView
     */
    private RecyclerView recyclerView;

    /**
     * 左侧商品回到上级目录按钮
     */
    private ImageView imageViewReturn;

    /**
     * 右侧会员卡号文本框
     */
    private TextView tv_customer;

    /**
     * GreedDao 对应的Dao
     * goodsDao 商品表
     * couponsDao 优惠券表
     * goodsCateDao 商品分类表
     * sellGoodHistoryDao 商品销售历史表
     * soldGoodDetailDao 商品详情表
     * userDao 会员表
     */
    private GoodsDao goodsDao = MyApplication.getDaoSession().getGoodsDao();
    private CouponsDao couponsDao = MyApplication.getDaoSession().getCouponsDao();
    private GoodsCateDao goodsCateDao = MyApplication.getDaoSession().getGoodsCateDao();
    private SellGoodHistoryDao sellGoodHistoryDao = MyApplication.getDaoSession().getSellGoodHistoryDao();
    private SoldGoodDetailDao soldGoodDetailDao = MyApplication.getDaoSession().getSoldGoodDetailDao();
    private UserDao userDao = MyApplication.getDaoSession().getUserDao();

    /**
     * 商品集合 左侧商品列表第三层具体商品集合
     */
    private List<Goods> goodsList = new ArrayList<>();
    /**
     * 商品一级分类集合 数据库获取全部的
     */
    private List<GoodsCate> goodBeanList = goodsCateDao.queryBuilder()
            .where(GoodsCateDao.Properties.Pid.eq(0)).list();
    /**
     * 商品二级分类集合 数据库获取符合父层一级分类的二级分类集合
     */
    private List<GoodsCate> goodsCateList = new ArrayList<>();
    /**
     * 左侧商品列表回退按钮 标志位 1，2，3，4，5 分别对应 左侧商品recyclerview展示的内容
     */
    private int p_ivretrun = 1;
    /**
     * 顶部搜索按钮
     */
    private TextView iv_searchview;
    /**
     * 商品集合 左侧商品第三层recyclerview对应的adapter
     */
    private CommonAdapter commonAdapter3;

    private TextView et_searchView;
    /**
     * 右侧放入购物车商品的recyclerview
     */
    private RecyclerView selling_recyclerView;
    /**
     * 右侧放入购物车商品的商品集合
     */
    private List<SellingGood> sellgoods = new ArrayList<>();
    /**
     * 底部绿色Pay按钮上的购买数量textview
     */
    private TextView tv_itemscount;
    /**
     * 底部绿色Pay按钮上的金额textview
     */
    private TextView tv_money;
    /**
     * 右侧税费textview
     */
    private TextView taxvat;
    /**
     * 右侧totalsave对应金额的textview
     */
    private TextView tv_discountoff;
    /**
     * 底部绿色Pay按钮
     */
    private ConstraintLayout bt_topay;
    /**
     * 黄色百分比打折按钮
     */
    private TextView tv_disbfb;
    /**
     * 绿色满减按钮
     */
    private TextView tv_dismoney;
    /**
     * 优惠券，会员卡等弹出dialog 错误提示信息的textview
     */
    private TextView tv_noticerror;

    /**
     * 响应扫描枪事件的标志位 0，1，2，3，4，5 分别对应 商品,打折,满减,会员,notes,search按钮弹出dialog的搜索商品
     */
    private int flag = 0;
    /**
     * 响应扫描枪事件的弹出错误信息的dialog
     */
    private AlertDialog dialog2;
    /**
     * 满减优惠减少的金额
     */
    private BigDecimal DiscountMoneyoff = BigDecimal.valueOf(0);
    /**
     * 打折优惠券的优惠力度
     */
    private double Discountbfboff = 0;
    /**
     * 打折优惠券使用条件
     */
    private double DiscountRequirementA = 0;

    /**
     * 满减优惠券使用条件
     */
    private double DiscountRequirementB = 0;

    /**
     * 左侧商品购物车未进行满减的总价格(但可能进行打折了)
     */
    private BigDecimal bigDecimal_wjj = BigDecimal.valueOf(0);
    /**
     * 左侧商品购物车未进行任何减价的总价格
     */
    private BigDecimal totalmoneyNoDis = BigDecimal.valueOf(0);
    private BigDecimal totalmoneyNoDisExNoDis = BigDecimal.valueOf(0);


    private String t;
    /**
     * 优惠总金额 = 打折减少的+满减减少的
     */
    private String t2;
    private String t3;
    private View rootView;
    private String notes = "";


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_sub_sell, container, false);
            initView(rootView);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        return rootView;


    }


    private void initView(View view) {
        initRecyclerView(view);
        initSearchView(view);
        initPayView(view);
        initMainView(view);
        registerReceiver();
    }


    /**
     * Cancel,Void,Hold按钮事件
     *
     * @param view
     */


    private void initMainView(View view) {

        tv_customer = view.findViewById(R.id.et_customer);


        view.findViewById(R.id.textView3).setOnClickListener(v -> {
            if (sellgoods.size() > 0) {
                showConfrimDialog("Cancel", "Are you sure?", 1);
            }
        });
        view.findViewById(R.id.textView5).setOnClickListener(v -> {
            if (sellgoods.size() > 0) {
                showConfrimDialog("Void", "Are you sure?", 2);
            }
        });
        view.findViewById(R.id.textView4).setOnClickListener(v -> {
            if (sellgoods.size() > 0) {
//                showConfrimDialog("Table", "Are you sure?", 3);
                flag = 3;

                if(TextUtils.isEmpty(tv_customer.getText().toString())){
                    showDialog("Table");
                }else {
                    showConfrimDialog("Table", "Are you sure?", 3);
                }



            }
        });

    }

    /**
     * 初始化打折券，满减券，消费者卡号，notes，支付按钮和事件
     *
     * @param view
     */
    private void initPayView(View view) {
        tv_itemscount = view.findViewById(R.id.item_count);
        tv_discountoff = view.findViewById(R.id.tv_discountoff);
        tv_money = view.findViewById(R.id.tv_money);
        taxvat = view.findViewById(R.id.taxvat);
        bt_topay = view.findViewById(R.id.button_topay);
        tv_disbfb = view.findViewById(R.id.tv_alipay);
        tv_dismoney = view.findViewById(R.id.tv_card);


        tv_dismoney.setOnClickListener(v -> {
//            flag = 2;
//            showDialog("Promotion Code (£)");
            /***
             *
             *厨房单
             */
            if (sellgoods.size() > 0) {

                insertGoodsToHistory(sellgoods, 7);

            }

        });

        tv_disbfb.setOnClickListener(v -> {
            flag = 1;
            showDialog("Discount Off (%)");

        });

        view.findViewById(R.id.tv_cash).setOnClickListener(v -> {
//            flag = 3;
//            showDialog("Table");
            /***
             *
             *打印客户单
             */

            if (sellgoods.size() > 0) {

                insertGoodsToHistory(sellgoods, 6);

            }

        });

        view.findViewById(R.id.tv_Notes).setOnClickListener(v -> {
            flag = 4;
            showDialog("Add Notes");

        });


        bt_topay.setOnClickListener(v -> {

            if (sellgoods.size() > 0) {
                /**
                 * 计算商品价格优惠税率等
                 */
                insertGoodsToHistory(sellgoods, 5);

            }

        });


    }

    /**
     * 初始化商品搜索按钮和事件
     *
     * @param view
     */
    private void initSearchView(View view) {
        iv_searchview = view.findViewById(R.id.iv_search);
        et_searchView = view.findViewById(R.id.et_search);

        iv_searchview.setOnClickListener(v -> {
            flag = 5;
            showDialog("Search Product");

        });

    }

    /***
     * 初始化四个recyclerview
     * @param view
     */
    private void initRecyclerView(View view) {
        nestedScrollView = view.findViewById(R.id.scrollView);
        recyclerView = view.findViewById(R.id.sell_recyclerView);
        selling_recyclerView = view.findViewById(R.id.selling_recyclerview);
        selling_recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        imageViewReturn = view.findViewById(R.id.iv_return);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 5));


        commonAdapter3 = new CommonAdapter<Goods>(getContext(), R.layout.item_sell_good3, goodsList) {

            @Override
            protected void convert(ViewHolder holder, Goods goods, int position) {
                holder.setText(R.id.tv_foodname, goods.getEn_name() + goods.getName());
                holder.itemView.setOnClickListener(v -> {

                    TobuyGoods(goods, 1);
                    setPayText();
                    selling_recyclerView.getAdapter().notifyDataSetChanged();
                    selling_recyclerView.scrollToPosition(goodsList.size() - 1);
                    nestedScrollView.fullScroll(View.FOCUS_DOWN);//滚到底部
                });
            }
        };


        CommonAdapter commonAdapter2 = new CommonAdapter<GoodsCate>(getContext(), R.layout.item_sell_good2, goodsCateList) {

            @Override
            protected void convert(ViewHolder holder, GoodsCate goodsCate, int position) {
                holder.setText(R.id.tv_foodname, goodsCate.getEn_name());

                holder.itemView.setOnClickListener(v -> {
                    goodsList.clear();
                    goodsList.addAll(goodsDao.queryBuilder()
                            .where(GoodsDao.Properties.Type_id.eq(goodsCate.getId()))
                            .list());
                    recyclerView.setAdapter(commonAdapter3);
                    commonAdapter3.notifyDataSetChanged();
                    p_ivretrun = 3;
                });
            }
        };


        CommonAdapter commonAdapter = new CommonAdapter<GoodsCate>(getContext(), R.layout.item_sell_good, goodBeanList) {


            @Override
            protected void convert(ViewHolder holder, GoodsCate goodsCate, int position) {
                holder.setText(R.id.tv_foodname, goodsCate.getEn_name());
                holder.itemView.setOnClickListener(v -> {
                    imageViewReturn.setVisibility(View.VISIBLE);
//                    recyclerView.setBackgroundResource(R.color.itmebg);
                    goodsCateList.clear();
                    goodsCateList.addAll(goodsCateDao.queryBuilder()
                            .where(GoodsCateDao.Properties.Pid.eq(goodsCate.getId())).list());

                    recyclerView.setAdapter(commonAdapter2);
                    commonAdapter2.notifyDataSetChanged();
                    p_ivretrun = 2;
                });

            }
        };


        recyclerView.setAdapter(commonAdapter);

        imageViewReturn.setOnClickListener(v -> {


            if (p_ivretrun == 3) {
                recyclerView.setAdapter(commonAdapter2);
                p_ivretrun = 2;
            } else if (p_ivretrun == 2) {
                imageViewReturn.setVisibility(View.GONE);
                recyclerView.setAdapter(commonAdapter);
                p_ivretrun = 1;
            } else if (p_ivretrun == 4) {
                imageViewReturn.setVisibility(View.GONE);

                recyclerView.setAdapter(commonAdapter);
                p_ivretrun = 1;
            }


        });


        selling_recyclerView.setAdapter(new CommonAdapter<SellingGood>(getContext(), R.layout.item_selling_good, sellgoods) {
            @Override
            protected void convert(ViewHolder holder, SellingGood sellingGood, int position) {
                holder.setText(R.id.selling_number, sellingGood.getBuy_count() + "");
                if (sellingGood.getNo_discount().equals("false")) {
                    holder.setTextColorRes(R.id.selling_number, R.color.primary_color);
                } else {
                    holder.setTextColorRes(R.id.selling_number, R.color.black);
                }
                double b = sellingGood.getSell_price();
                BigDecimal p = BigDecimal.valueOf(b);
                String t_price = XMathUtil.multiply(sellingGood.getBuy_count(), sellingGood.getSell_price()).setScale(2, BigDecimal.ROUND_DOWN).toString();
                holder.setText(R.id.tv_selling_money, "£" + t_price);
                holder.setText(R.id.tv_goodname, sellingGood.getEn_name());
                holder.setText(R.id.tv_goodCname, sellingGood.getName());
                holder.setText(R.id.tv_good_disoff, new Double(sellingGood.getDiscountoff()).intValue() + "%");
                holder.setOnClickListener(R.id.iv_ljt, v -> {
                    BigDecimal bigDecimal = XMathUtil.subtract(totalmoneyNoDisExNoDis, new BigDecimal(t_price)).setScale(2, BigDecimal.ROUND_DOWN);


                    if (bigDecimal.doubleValue() < DiscountRequirementA) {
//                        showErrorDialog("再删除就不满足打折使用条件了！");
                        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_timeout, null, false);
                        Dialog timeoutDialog = new AlertDialog.Builder(getContext()).setView(view).create();
                        timeoutDialog.setCanceledOnTouchOutside(false);
                        timeoutDialog.show();
                        timeoutDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

                        TextView tv_confirm_card = view.findViewById(R.id.tv_confirm);
                        TextView tv_cancel_card = view.findViewById(R.id.tv_cancel);
                        TextView tv_msg = view.findViewById(R.id.tv_change);

                        tv_msg.setText("再删除就不满足打折使用条件了！确认删除吗？");


                        tv_cancel_card.setOnClickListener(view1 -> {
                            timeoutDialog.dismiss();

                        });

                        tv_confirm_card.setOnClickListener(view1 -> {
                            timeoutDialog.dismiss();
                            DiscountRequirementA = 0;
                            Discountbfboff = 0;
                            if (bigDecimal.doubleValue() < DiscountRequirementB) {
                                DiscountRequirementB = 0;
                                DiscountMoneyoff = BigDecimal.valueOf(0);
                            }

                            sellgoods.remove(sellingGood);
                            for (SellingGood sellingGood1 : sellgoods) {
                                sellingGood1.setDiscountoff(0);
                            }
                            notifyDataSetChanged();
                            setPayText();

                        });
                    } else if (bigDecimal.doubleValue() < DiscountRequirementB) {
//                        showErrorDialog("再删除就不满足满减使用条件了！");
                        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_timeout, null, false);
                        Dialog timeoutDialog = new AlertDialog.Builder(getContext()).setView(view).create();
                        timeoutDialog.setCanceledOnTouchOutside(false);
                        timeoutDialog.show();
                        timeoutDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

                        TextView tv_confirm_card = view.findViewById(R.id.tv_confirm);
                        TextView tv_cancel_card = view.findViewById(R.id.tv_cancel);
                        TextView tv_msg = view.findViewById(R.id.tv_change);

                        tv_msg.setText("再删除就不满足满减使用条件了！确认删除吗？");


                        tv_cancel_card.setOnClickListener(view1 -> {
                            timeoutDialog.dismiss();

                        });

                        tv_confirm_card.setOnClickListener(view1 -> {
                            timeoutDialog.dismiss();
                            DiscountRequirementB = 0;
                            DiscountMoneyoff = BigDecimal.valueOf(0);
                            sellgoods.remove(sellingGood);
                            notifyDataSetChanged();
                            setPayText();

                        });
                    } else {
                        sellgoods.remove(sellingGood);
                        notifyDataSetChanged();
                        setPayText();
                    }


                });

                holder.itemView.setOnClickListener(v -> {
                    showDialog(sellingGood);
                });
            }
        });


    }


    /**
     * 添加商品前的判断
     *
     * @param goods 将要放入购物车的商品
     * @param num   商品购买数量
     */
    private void TobuyGoods(Goods goods, int num) {
        int l = sellgoods.size();

        for (int i = 0; i < l; i++) {
            if (sellgoods.get(i).getId() == goods.getId()) {
                int a = sellgoods.get(i).getBuy_count();
                sellgoods.get(i).setBuy_count(a + 1);
                return;
            }
        }
        DecimalFormat df = new DecimalFormat("#0.00");
        double vat = 0.00;
        String sellprice = df.format(goods.getSell_price());
        double sp = 0.00;
        String ss = goods.getVat_percentage();
        try {

            vat = Double.parseDouble(ss);
            sp = Double.parseDouble(sellprice);
        } catch (Exception e) {
            System.out.println("捕获转换异常：" + e);
        }

        if (goods.getNo_discount().equals("false")) {
            sellgoods.add(new SellingGood(goods.getId(), goods.getEn_name(), goods.getName(), num, sp, vat, goods.getNo_discount(), goods.getHot_goods(), Discountbfboff));
        } else {
            sellgoods.add(new SellingGood(goods.getId(), goods.getEn_name(), goods.getName(), num, sp, vat, goods.getNo_discount(), goods.getHot_goods(), 0));
        }


    }

    /**
     * 顶部Cancel,Void,Hold按钮点击弹出dialog事件处理
     *
     * @param title 标题
     * @param msg   提示信息
     * @param flag  标志位 1，2，3 对应 Cancel,Void,Hold,
     */

    private void showConfrimDialog(String title, String msg, int flag) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_confirm, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(getContext()).setView(view).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        //此处设置位置窗体大小，我这里设置为了手机屏幕宽度的3/4  注意一定要在show方法调用后再写设置窗口大小的代码，否则不起效果会
        dialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv_title = view.findViewById(R.id.tv_number);
        TextView tv_msg = view.findViewById(R.id.et_number);
        tv_title.setText(title);
        tv_msg.setText(msg);
        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
            dialog.dismiss();
        });
        view.findViewById(R.id.tv_confirm).setOnClickListener(v -> {
            DiscountMoneyoff = new BigDecimal(0);
            totalmoneyNoDisExNoDis = new BigDecimal(0);
            Discountbfboff = 0;
            DiscountRequirementA = 0;
            DiscountRequirementB = 0;

            List<SellGoodHistory> s=sellGoodHistoryDao.queryBuilder().where(SellGoodHistoryDao.Properties.CustomerCode.eq(tv_customer.getText().toString())
                    , SellGoodHistoryDao.Properties.PayStatus.eq(3)).list();

            if(s.size()>0){
                sellGoodHistoryDao.delete(s.get(0));
            }






            insertGoodsToHistory(sellgoods, flag);
            sellgoods.clear();
            selling_recyclerView.getAdapter().notifyDataSetChanged();
            setPayText();
            tv_customer.setText("");
            dialog.dismiss();

        });

    }


    /**
     * 打折,满减,会员卡,notes,search按钮点击响应dialog
     *
     * @param str 文字标题
     */
    private void showDialog(String str) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_edit, null, false);
        dialog2 = new AlertDialog.Builder(getContext()).setView(view).create();
        dialog2.show();
        dialog2.setCanceledOnTouchOutside(false);
        //此处设置位置窗体大小，我这里设置为了手机屏幕宽度的3/4  注意一定要在show方法调用后再写设置窗口大小的代码，否则不起效果会
        dialog2.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView textView = view.findViewById(R.id.tv_number);
        tv_noticerror = view.findViewById(R.id.textView11);
        textView.setText(str);

        EditText editText = view.findViewById(R.id.et_number);

        if (flag == 5) {
            editText.setInputType(InputType.TYPE_CLASS_TEXT);
        } else if (flag == 4) {
            editText.setInputType(InputType.TYPE_CLASS_TEXT);
            editText.setText(notes);
        } else {
            editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        }


        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
            flag = 0;
            tv_noticerror.setVisibility(View.INVISIBLE);
            dialog2.dismiss();

        });
        view.findViewById(R.id.tv_confirm).setOnClickListener(v -> {
            String a = editText.getText().toString();

            if (flag == 5) {
                String searchstr = "%" + a + "%";
                goodsList.clear();
                List<Goods> s = goodsDao.queryBuilder()
                        .whereOr(GoodsDao.Properties.En_name.like(searchstr),
                                GoodsDao.Properties.Name.like(searchstr),
                                GoodsDao.Properties.Bar_code.like(searchstr),
                                GoodsDao.Properties.Goods_code.like(searchstr),
                                GoodsDao.Properties.Bar_code_1.like(searchstr),
                                GoodsDao.Properties.Bar_code_2.like(searchstr),
                                GoodsDao.Properties.Bar_code_3.like(searchstr),
                                GoodsDao.Properties.Bar_code_4.like(searchstr),
                                GoodsDao.Properties.Bar_code_5.like(searchstr))
                        .list();
                if (s.size() > 0) {
                    goodsList.addAll(s);
                    recyclerView.setBackgroundResource(R.color.itmebg);
                    recyclerView.setAdapter(commonAdapter3);
                    imageViewReturn.setVisibility(View.VISIBLE);
                    p_ivretrun = 4;

                    if (isKeyboardVisbility(getContext(), iv_searchview)) {
                        hideKeyboard(iv_searchview);
                    }
                    flag = 0;
                    dialog2.dismiss();
                } else {
                    tv_noticerror.setVisibility(View.VISIBLE);
                    tv_noticerror.setText("Promotion code is invalid");
                }

            } else if (flag == 1) {

                if (Integer.parseInt(a) < 100) {


                    Discountbfboff = Integer.parseInt(a);


                    for (SellingGood sellingGood : sellgoods) {

                        if (sellingGood.getNo_discount().equals("false")) {
                            sellingGood.setDiscountoff(Discountbfboff);
                        } else {

                        }

                    }

                    flag = 0;
                    dialog2.dismiss();
                    setPayText();
                    selling_recyclerView.getAdapter().notifyDataSetChanged();

                }


            } else if (flag == 2) {

                List<Coupons> couponsList = couponsDao.queryBuilder()
                        .where(CouponsDao.Properties.Code_num.eq(a), CouponsDao.Properties.Status.eq("0")).list();

                if (couponsList.size() != 1) {
                    tv_noticerror.setVisibility(View.VISIBLE);
                    tv_noticerror.setText("Promotion code is invalid");
//                    Toast.makeText(getContext(), "Bar_code error", Toast.LENGTH_SHORT).show();
                } else {
                    Coupons coupon = couponsList.get(0);
                    double b = Double.parseDouble(coupon.getMoney());
                    double c = Double.parseDouble(coupon.getRequirement());
                    if (totalmoneyNoDisExNoDis.doubleValue() >= c) {
                        DiscountRequirementB = c;
                        DiscountMoneyoff = BigDecimal.valueOf(b);
                        flag = 0;
                        dialog2.dismiss();
                        setPayText();
                        selling_recyclerView.getAdapter().notifyDataSetChanged();
                    } else {
                        tv_noticerror.setVisibility(View.VISIBLE);
                        tv_noticerror.setText("不满足使用条件");
//                        Toast.makeText(getContext(), "不满足使用条件", Toast.LENGTH_SHORT).show();
                    }

                }


            } else if (flag == 3) {

                List<User> userList = userDao.queryBuilder().where(UserDao.Properties.Card_number.eq(a)).list();

                List<SellGoodHistory> sellGoodHistories = sellGoodHistoryDao.queryBuilder().where(SellGoodHistoryDao.Properties.PayStatus.eq(3),
                        SellGoodHistoryDao.Properties.CustomerCode.eq(a)).list();


                if (userList.size() != 1 || sellGoodHistories.size() != 0) {
                    tv_noticerror.setVisibility(View.VISIBLE);
                    tv_noticerror.setText("This table is used");
//                    Toast.makeText(getContext(), "Bar_code error", Toast.LENGTH_SHORT).show();
                } else {
                    User user = userList.get(0);
                    tv_customer.setText(user.getCard_number());
                    flag = 0;
                    dialog2.dismiss();
                    showConfrimDialog("Table", "Are you sure?", 3);
                }

            } else if (flag == 4) {

                notes = a;
                flag = 0;
                dialog2.dismiss();
            }


//            tv_noticerror.setVisibility(View.INVISIBLE);


        });
    }

    private void showErrorDialog(String msg) {
//        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
        new XToast<>(MyApplication.getInstance())
                .setDuration(1000)
                .setContentView(R.layout.toast_hint)
                .setAnimStyle(android.R.style.Animation_Activity)
                .setImageDrawable(android.R.id.icon, R.mipmap.ic_dialog_tip_warning)
                .setText(android.R.id.message, msg)
                .show();
    }

    /**
     * 点击购物车商品列表某项弹出的dialog展示商品信息
     *
     * @param sellingGood
     */
    private void showDialog(SellingGood sellingGood) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_good_detail, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(getContext()).setView(view).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        //此处设置位置窗体大小，我这里设置为了手机屏幕宽度的3/4  注意一定要在show方法调用后再写设置窗口大小的代码，否则不起效果会
        dialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv_goodname = view.findViewById(R.id.tv_name);
        tv_goodname.setText(sellingGood.getEn_name());

//        TextView tv_vat = view.findViewById(R.id.tv_vat);
//        tv_vat.setText(sellingGood.getVat() + "%");

        TextView tv_unitprice = view.findViewById(R.id.tv_unitprice);

        tv_unitprice.setText(sellingGood.getSell_price() + "");

        EditText et_number = view.findViewById(R.id.et_number);
        et_number.setText(sellingGood.getBuy_count() + "");

        TextView et_dis = view.findViewById(R.id.et_dis);
        et_dis.setText(new Double(sellingGood.getDiscountoff()).intValue() + "");


        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        tv_confirm.setOnClickListener(v -> {

//            String a=et_dis.getText().toString();

            Double discount = Double.parseDouble(et_dis.getText().toString());
            Integer number = Integer.parseInt(et_number.getText().toString());
            if (discount > 100 || discount < 0) {

                new XToast<>(MyApplication.getInstance())
                        .setDuration(1000)
                        .setContentView(R.layout.toast_hint)
                        .setAnimStyle(android.R.style.Animation_Activity)
                        .setImageDrawable(android.R.id.icon, R.mipmap.ic_dialog_tip_error)
                        .setText(android.R.id.message, "Error")
                        .show();
                return;
            }

            if (number < 1) {
                new XToast<>(MyApplication.getInstance())
                        .setDuration(1000)
                        .setContentView(R.layout.toast_hint)
                        .setAnimStyle(android.R.style.Animation_Activity)
                        .setImageDrawable(android.R.id.icon, R.mipmap.ic_dialog_tip_error)
                        .setText(android.R.id.message, "Error")
                        .show();
//                Toast.makeText(getContext(), "Error", Toast.LENGTH_SHORT).show();
                return;
            }

            int n = sellingGood.getBuy_count() - number;

            String t_price = XMathUtil.multiply(n, sellingGood.getSell_price()).setScale(2, BigDecimal.ROUND_DOWN).toString();
            BigDecimal bigDecimal = XMathUtil.subtract(totalmoneyNoDisExNoDis, new BigDecimal(t_price)).setScale(2, BigDecimal.ROUND_DOWN);

            if (sellingGood.getBuy_count() > number) {
                if (bigDecimal.doubleValue() < DiscountRequirementA) {
                    showErrorDialog("再删除就不满足打折使用条件了！");

                    View view3 = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_timeout, null, false);
                    Dialog timeoutDialog = new AlertDialog.Builder(getContext()).setView(view3).create();
                    timeoutDialog.setCanceledOnTouchOutside(false);
                    timeoutDialog.show();
                    timeoutDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

                    TextView tv_confirm_card = view3.findViewById(R.id.tv_confirm);
                    TextView tv_cancel_card = view3.findViewById(R.id.tv_cancel);
                    TextView tv_msg = view3.findViewById(R.id.tv_change);

                    tv_msg.setText("再删除就不满足打折使用条件了！确认删除吗？");


                    tv_cancel_card.setOnClickListener(view1 -> {
                        timeoutDialog.dismiss();

                    });

                    tv_confirm_card.setOnClickListener(view1 -> {
                        timeoutDialog.dismiss();
                        DiscountRequirementA = 0;
                        Discountbfboff = 0;
                        if (bigDecimal.doubleValue() < DiscountRequirementB) {
                            DiscountRequirementB = 0;
                            DiscountMoneyoff = BigDecimal.valueOf(0);
                        }

                        sellingGood.setBuy_count(number);
//                        sellingGood.setDiscountoff(discount);

                        for (SellingGood sellingGood1 : sellgoods) {
                            sellingGood1.setDiscountoff(0);
                        }


                        selling_recyclerView.getAdapter().notifyDataSetChanged();
                        setPayText();
                        dialog.dismiss();

                    });


                    return;
                }
                if (bigDecimal.doubleValue() < DiscountRequirementB) {
                    showErrorDialog("再删除就不满足满减使用条件了！");

                    View view3 = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_timeout, null, false);
                    Dialog timeoutDialog = new AlertDialog.Builder(getContext()).setView(view3).create();
                    timeoutDialog.setCanceledOnTouchOutside(false);
                    timeoutDialog.show();
                    timeoutDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

                    TextView tv_confirm_card = view3.findViewById(R.id.tv_confirm);
                    TextView tv_cancel_card = view3.findViewById(R.id.tv_cancel);
                    TextView tv_msg = view3.findViewById(R.id.tv_change);

                    tv_msg.setText("再删除就不满足满减使用条件了！确认删除吗？");


                    tv_cancel_card.setOnClickListener(view1 -> {
                        timeoutDialog.dismiss();

                    });

                    tv_confirm_card.setOnClickListener(view1 -> {
                        timeoutDialog.dismiss();
                        DiscountRequirementB = 0;
                        DiscountMoneyoff = BigDecimal.valueOf(0);
                        sellingGood.setBuy_count(number);
                        sellingGood.setDiscountoff(discount);

                        selling_recyclerView.getAdapter().notifyDataSetChanged();
                        setPayText();
                        dialog.dismiss();

                    });

                    return;
                }
            }


            sellingGood.setBuy_count(number);
            sellingGood.setDiscountoff(discount);

            selling_recyclerView.getAdapter().notifyDataSetChanged();
            setPayText();
            dialog.dismiss();
        });

        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
            dialog.dismiss();
        });

    }


    private void setPayText() {
        int count = sellgoods.size();
        int number = 0;

        BigDecimal totalVal = BigDecimal.valueOf(0);
        BigDecimal totalmoney = BigDecimal.valueOf(0);
        BigDecimal totalmoneyNoDis = BigDecimal.valueOf(0);
        BigDecimal totalDiscountoff = BigDecimal.valueOf(0);
        /***
         *
         * 不包含不可以打折商品的总价格（不打折商品总价+未打折商品总计）
         */
        BigDecimal totalmoneyNoDisExNoDis = BigDecimal.valueOf(0);

        for (SellingGood sellingGood : sellgoods) {
            ProductResultBean p = ProductResultUtils.abs(sellingGood.getSell_price(), sellingGood.getBuy_count(), sellingGood.getDiscountoff(), sellingGood.getVat());
            totalmoneyNoDis = XMathUtil.add(totalmoneyNoDis, p.getT_price()).setScale(2, BigDecimal.ROUND_DOWN);
            totalmoney = XMathUtil.add(totalmoney, p.getT_d_sp()).setScale(2, BigDecimal.ROUND_DOWN);
            totalVal = XMathUtil.add(totalVal, p.getT_vat()).setScale(2, BigDecimal.ROUND_DOWN);
            number += sellingGood.getBuy_count();
            if (sellingGood.getNo_discount().equals("false")) {
                totalmoneyNoDisExNoDis = XMathUtil.add(totalmoneyNoDisExNoDis, p.getT_price()).setScale(2, BigDecimal.ROUND_DOWN);
            } else {

            }


        }
        tv_itemscount.setText(number + "  items");
        totalDiscountoff = XMathUtil.subtract(totalmoneyNoDis, totalmoney);
        this.totalmoneyNoDis = totalmoneyNoDis;
        this.totalmoneyNoDisExNoDis = totalmoneyNoDisExNoDis;
        bigDecimal_wjj = totalmoney;

        totalmoney = XMathUtil.subtract(totalmoney, DiscountMoneyoff).setScale(2, BigDecimal.ROUND_DOWN);
        if (DiscountMoneyoff.doubleValue() > 0 && totalDiscountoff.doubleValue() > 0) {
//            XMathUtil.add(totalDiscountoff,DiscountMoneyoff);
            t2 = XMathUtil.add(totalDiscountoff, DiscountMoneyoff).setScale(2, BigDecimal.ROUND_DOWN).toString();
            tv_discountoff.setText("-£" + t2);
        } else if (totalDiscountoff.doubleValue() > 0) {

            t2 = totalDiscountoff.setScale(2, BigDecimal.ROUND_DOWN).toString();
            tv_discountoff.setText("-£" + t2);

        } else if (DiscountMoneyoff.doubleValue() > 0) {
            t2 = DiscountMoneyoff.setScale(2, BigDecimal.ROUND_DOWN).toString();
            tv_discountoff.setText("-£" + t2);
        } else {
            t2 = "0.00";
            tv_discountoff.setText("-£0.00");

        }
        tv_money.setText("£" + totalmoney);
        taxvat.setText("£" + totalVal);
        t3 = totalVal.toString();
        t = totalmoney.toString();


    }

    /**
     * 判断软键盘输入法是否弹出
     */
    public boolean isKeyboardVisbility(Context context, View v) {
        InputMethodManager imm = (InputMethodManager)
                context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.hideSoftInputFromWindow(v.getWindowToken(), 0)) {
            imm.showSoftInput(v, 0);
            return true;//键盘显示中
        } else {
            return false;//键盘未显示
        }
    }

    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }


    private static final String ACTION_DATA_CODE_RECEIVED =
            "com.sunmi.scanner.ACTION_DATA_CODE_RECEIVED";
    private static final String DATA = "data";
    private static final String SOURCE = "source_byte";
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (getParentFragment().getParentFragment().getUserVisibleHint() && getParentFragment().getUserVisibleHint() && getUserVisibleHint()) {
                String a = "";
            } else {
                String a = "";
            }

            String code = intent.getStringExtra(DATA);
//            String arr = intent.getByteArrayExtra(SOURCE);
            if (code != null && !code.isEmpty()) {
//                mCode.setText(code);

//                Toast.makeText(getContext(),code,Toast.LENGTH_SHORT).show();

                String a = code.trim().toString();

                if (flag == 0) {

                    List<Goods> goodlist = goodsDao.queryBuilder()
                            .whereOr(GoodsDao.Properties.Bar_code_1.eq(a),
                                    GoodsDao.Properties.Bar_code_2.eq(a),
                                    GoodsDao.Properties.Bar_code_3.eq(a),
                                    GoodsDao.Properties.Bar_code_4.eq(a),
                                    GoodsDao.Properties.Bar_code_5.eq(a)).list();

                    if (goodlist.size() != 1) {
//                        Toast.makeText(getContext(), "Bar_code error", Toast.LENGTH_SHORT).show();
                        new XToast<>(MyApplication.getInstance())
                                .setDuration(1000)
                                .setContentView(R.layout.toast_hint)
                                .setAnimStyle(android.R.style.Animation_Activity)
                                .setImageDrawable(android.R.id.icon, R.mipmap.ic_dialog_tip_error)
                                .setText(android.R.id.message, "Bar_code_Error")
                                .show();
                    } else {
                        TobuyGoods(goodlist.get(0), 1);
                        setPayText();
                        selling_recyclerView.getAdapter().notifyDataSetChanged();
                    }


                } else if (flag == 1) {

                    List<Coupons> couponsList = couponsDao.queryBuilder()
                            .where(CouponsDao.Properties.Code_num.eq(a), CouponsDao.Properties.Status.eq("1")).list();

                    if (couponsList.size() != 1) {
//                        Toast.makeText(getContext(), "Bar_code error", Toast.LENGTH_SHORT).show();
                        tv_noticerror.setVisibility(View.VISIBLE);
                        tv_noticerror.setText("Promotion code is invalid");
                    } else {
                        Coupons coupon = couponsList.get(0);
                        double b = Double.parseDouble(coupon.getDiscount());
                        double c = Double.parseDouble(coupon.getRequirement());

                        if (b < 100) {
                            if (totalmoneyNoDisExNoDis.doubleValue() >= c) {
                                DiscountRequirementA = c;
                                Discountbfboff = b;
                                for (SellingGood sellingGood : sellgoods) {

                                    if (sellingGood.getNo_discount().equals("false")) {
                                        sellingGood.setDiscountoff(Discountbfboff);
                                    } else {

                                    }

                                }
                                flag = 0;
                                dialog2.dismiss();
                                setPayText();
                                selling_recyclerView.getAdapter().notifyDataSetChanged();

                            } else {
                                tv_noticerror.setVisibility(View.VISIBLE);
//                            Toast.makeText(getContext(), "Bar_code error", Toast.LENGTH_SHORT).show();
                                tv_noticerror.setText("不满足使用条件");
//                                showErrorDialog("不满足使用条件！");
                            }
                        }


                    }


                } else if (flag == 2) {

                    List<Coupons> couponsList = couponsDao.queryBuilder()
                            .where(CouponsDao.Properties.Code_num.eq(a), CouponsDao.Properties.Status.eq("0")).list();

                    if (couponsList.size() != 1) {
                        tv_noticerror.setVisibility(View.VISIBLE);
                        tv_noticerror.setText("Promotion code is invalid");
//                        Toast.makeText(getContext(), "Bar_code error", Toast.LENGTH_SHORT).show();
                    } else {
                        Coupons coupon = couponsList.get(0);
                        double b = Double.parseDouble(coupon.getMoney());
                        double c = Double.parseDouble(coupon.getRequirement());
                        if (totalmoneyNoDisExNoDis.doubleValue() >= c) {
                            DiscountRequirementB = c;
                            DiscountMoneyoff = BigDecimal.valueOf(b);
                            tv_noticerror.setVisibility(View.INVISIBLE);
                            dialog2.dismiss();
                            flag = 0;
                            setPayText();
                            selling_recyclerView.getAdapter().notifyDataSetChanged();
                        } else {
                            tv_noticerror.setVisibility(View.VISIBLE);
//                            tv_noticerror.setText("Promotion code is invalid");
                            tv_noticerror.setText("不满足使用条件");
//                            Toast.makeText(getContext(), "Bar_code error", Toast.LENGTH_SHORT).show();
                        }

                    }


                } else if (flag == 3) {

                    List<User> userList = userDao.queryBuilder().where(UserDao.Properties.Card_number.eq(a)).list();
                    if (userList.size() != 1) {
                        tv_noticerror.setVisibility(View.VISIBLE);
                        tv_noticerror.setText("Promotion code is invalid");
//                        Toast.makeText(getContext(), "Bar_code error", Toast.LENGTH_SHORT).show();
                    } else {
                        User user = userList.get(0);
                        tv_customer.setText(user.getCard_number());
                    }


                }


            }
        }
    };

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_DATA_CODE_RECEIVED);
        getActivity().registerReceiver(receiver, filter);
    }


    /**
     * SubSellFragment 和 SubPayFragment 跳转调用的方法
     *
     * @param sellGoodHistory
     */
    public void go(SellGoodHistory sellGoodHistory) {

        sellgoods.clear();
        if(sellGoodHistory!=null&&sellGoodHistory.getCustomerCode()!=null){
            tv_customer.setText(sellGoodHistory.getCustomerCode());
        }

        DiscountMoneyoff = BigDecimal.valueOf(0);
        Discountbfboff = 0;
        totalmoneyNoDisExNoDis = new BigDecimal(0);
        DiscountRequirementA = 0;
        DiscountRequirementB = 0;

        setPayText();
        selling_recyclerView.getAdapter().notifyDataSetChanged();
        if (sellGoodHistory != null) {
            List<SoldGoodDetail> soldGoodDetails = sellGoodHistory.getSoldGoodDetails();

            for (SoldGoodDetail soldGoodDetail : soldGoodDetails) {
                long a = soldGoodDetail.getProductId();
                List<Goods> goodsList = goodsDao.queryBuilder().where(GoodsDao.Properties.Id.eq(soldGoodDetail.getProductId())).list();
                TobuyGoods(goodsList.get(0), soldGoodDetail.getNumber().intValue());
                setPayText();
            }


        }
        selling_recyclerView.getAdapter().notifyDataSetChanged();


    }


    /**
     * 计算商品价格优惠税率等 主要目的为存入销售历史表
     *
     * @param sellingGoodList 右侧放入购物车商品的商品集合
     * @param status          状态 表示是点击那个按钮进行的这个事件 1,2,3,4 对应cancel void hold pay按钮
     */
    private void insertGoodsToHistory(List<SellingGood> sellingGoodList, int status) {
        List<SoldGoodDetail> soldGoodDetails = new ArrayList<>();

        int count = sellgoods.size();

        int number = 0;

        tv_itemscount.setText(count + "  items");
        BigDecimal totalVat = BigDecimal.valueOf(0);
        BigDecimal totalmoney = BigDecimal.valueOf(0);
        BigDecimal totalmoneyNoDis = BigDecimal.valueOf(0);

        BigDecimal totalDiscountoff = BigDecimal.valueOf(0);
        for (SellingGood sellingGood : sellingGoodList) {

            ProductResultBean p = ProductResultUtils.abs(sellingGood.getSell_price(), sellingGood.getBuy_count(), sellingGood.getDiscountoff(), sellingGood.getVat());
            totalmoneyNoDis = XMathUtil.add(totalmoneyNoDis, p.getT_price()).setScale(2, BigDecimal.ROUND_DOWN);
            totalmoney = XMathUtil.add(totalmoney, p.getT_d_sp()).setScale(2, BigDecimal.ROUND_DOWN);
            totalVat = XMathUtil.add(totalVat, p.getT_vat()).setScale(2, BigDecimal.ROUND_DOWN);
            SoldGoodDetail soldGoodDetail = new SoldGoodDetail();
            soldGoodDetail.setId(null);
            soldGoodDetail.setProductId(sellingGood.getId());
            soldGoodDetail.setChineseName(sellingGood.getName());
            soldGoodDetail.setEnglishName(sellingGood.getEn_name());
            soldGoodDetail.setNumber((long) sellingGood.getBuy_count());
            soldGoodDetail.setTotalPrice(p.getT_price().doubleValue());
            soldGoodDetail.setPrice(sellingGood.getSell_price());
            soldGoodDetail.setVat(sellingGood.getVat());
            soldGoodDetail.setPriceAfterDis(p.getDis_sell_price().doubleValue());
            soldGoodDetail.setDiscount(sellingGood.getDiscountoff() + "");
            soldGoodDetail.setTotalPriceAfterDis(p.getT_d_sp().doubleValue());
            soldGoodDetail.setTotalPrice(p.getT_price().doubleValue());
            soldGoodDetail.setVatMoney(p.getT_vat().doubleValue());
            soldGoodDetail.setHot_goods(sellingGood.getHot_goods());
            soldGoodDetail.setNo_discount(sellingGood.getNo_discount());
            soldGoodDetails.add(soldGoodDetail);
            number += sellingGood.getBuy_count();
        }

        totalDiscountoff = XMathUtil.subtract(totalmoneyNoDis, totalmoney);
        this.totalmoneyNoDis = totalmoneyNoDis;
        bigDecimal_wjj = totalmoney;
        totalmoney = XMathUtil.subtract(totalmoney, DiscountMoneyoff);
        BigDecimal total_dis = XMathUtil.subtract(totalmoneyNoDis, totalmoney);
        SellGoodHistory sellGoodHistory = new SellGoodHistory();
        sellGoodHistory.setId(null);
        sellGoodHistory.setOrderCode("");
        sellGoodHistory.setCashierId(MyApplication.UserId);
        sellGoodHistory.setCashRegisterId(MyApplication.MachineId);
        sellGoodHistory.setTotalNumber(number);
        sellGoodHistory.setCustomerCode(tv_customer.getText().toString());
        sellGoodHistory.setRemarks(notes);
        sellGoodHistory.setPaymentMethod(0);
        sellGoodHistory.setTotalMoney(bigDecimal_wjj + "");
        sellGoodHistory.setTotalMoneyAfterDiscount(totalmoney + "");
        sellGoodHistory.setTotalVat(totalVat + "");
        sellGoodHistory.setTotalSave(total_dis + "");
        sellGoodHistory.setPayStatus(status);
        sellGoodHistory.setPayTime(getSecondTimestamp(new Date()));
        sellGoodHistory.setChangeMoney("0");
        sellGoodHistory.setActualPayMoney("0");
        sellGoodHistory.setDiscountOffCode("");
        sellGoodHistory.setDicountRemCode("");
        sellGoodHistory.setSoldGoodDetailList(soldGoodDetails);

        if (status == 5) {
            SubSellingFragment subSellingFragment = (SubSellingFragment) getParentFragment();
            subSellingFragment.goShopping(1, sellGoodHistory, null);
        } else if (status == 6) {
            print(sellGoodHistory, 6);
        } else if (status == 7) {
            print2(sellGoodHistory);
        } else {
            Long id = sellGoodHistoryDao.insert(sellGoodHistory);
            for (SoldGoodDetail soldGoodDetail : soldGoodDetails) {
                soldGoodDetail.setSellGoodHistoryId(id);
            }
            soldGoodDetailDao.insertInTx(soldGoodDetails);
        }


    }


    /**
     * 获取精确到秒的时间戳
     *
     * @return
     */
    public static int getSecondTimestamp(Date date) {
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return Integer.valueOf(timestamp.substring(0, length - 3));
        } else {
            return 0;
        }
    }


    private void print(SellGoodHistory sellGoodHistory, int status) {
        if (pos_usb == null) {
            Toast.makeText(MyApplication.getInstance().getApplicationContext(), "Please connect the printer", Toast.LENGTH_LONG).show();
            return;
        }
        List<SoldGoodDetail> soldGoodDetailList = sellGoodHistory.getSoldGoodDetailList();
        String a = PrintUtil4.printxx(soldGoodDetailList);
//            System.out.print(a);
        if (status == 6) {
            printText(2,"No Pay", 1, 1, 20);
        }
        if(!TextUtils.isEmpty(sellGoodHistory.getCustomerCode())){
            printText(2,"Table"+sellGoodHistory.getCustomerCode(), 1, 1, 20);
        }
//        printText(2,"Table"+sellGoodHistory.getCustomerCode(), 1, 1, 20);
        printText("Golden Mayfair Chinese Restaurant", 1, 1, 20);
        printText("3 West Road", 1, 0, 20);
        printText("Westcliff-on-Sea, Essex,SS0 9AU", 1, 0, 20);
        printText("Telephone 01702352707", 1, 0, 20);
//        printText("VAT No 320498217", 1, 0, 20);
        printText("", 0, 0);
//        printText("Order Ref: " + orderCode, 0, 1);
        printText("------------------------------------------", 0, 0);
//            printText("Description                          Total", 0, 0);
//            printText("------------------------------------------", 0, 0);
        printText(a, 0, 1);
        printText("Total                                " + sellGoodHistory.getTotalMoney(), 0, 0);
//        printText("------------------------------------------", 0, 0);
//        printText("YOU SAVED  " + sellGoodHistory.getTotalSave(), 1, 1, 10);
        printText("------------------------------------------", 0, 0);
        printText("Grand Total                          " + sellGoodHistory.getTotalMoneyAfterDiscount(), 0, 1);
        printText("------------------------------------------", 0, 0);
        printText("Number Of Items                        " + sellGoodHistory.getTotalNumber() + "\n", 0, 1);
        printText("VAT Summary Breakdown", 1, 3, 30);
        printText("Total      VAT Value", 1, 1, 20);
        printText(sellGoodHistory.getTotalMoneyAfterDiscount() + "         " + sellGoodHistory.getTotalVat(), 1, 0, 20);
        printText("Payment Details\n", 0, 3);
//        printText("Paid By Cash                         " + giveCash, 0, 1, 20);
//        printText("Paid By "+payMethod+"                         " + giveCash, 0, 1, 20);
//        printText("Change                               " + changestr, 0, 1, 20);
//        printText("You have been Served By" + MyApplication.UserName, 1, 0, 20);
        printText("Till No:" + "Till" + MyApplication.getInstance().getMachineId(), 0, 1, 10);
        printText("", 1, 1, 10);
//        printBar(orderCode);
//        printText(time, 1, 1, 20);
//        printText("Please Keep for your records", 1, 0, 20);
        printText("Published Terms and Conditions Apply", 1, 0, 20);



        cutPaper();


    }


    private void print2(SellGoodHistory sellGoodHistory) {
        if (pos_usb == null) {
            Toast.makeText(MyApplication.getInstance().getApplicationContext(), "Please connect the printer", Toast.LENGTH_LONG).show();
            return;
        }
        List<SoldGoodDetail> soldGoodDetailList = sellGoodHistory.getSoldGoodDetailList();
        String a = PrintUtil4.printxx(soldGoodDetailList);
        if(!TextUtils.isEmpty(sellGoodHistory.getCustomerCode())){
            printText(2,"Table"+sellGoodHistory.getCustomerCode(), 1, 1, 20);
        }
        printText(2, a, 0, 1);
        cutPaper();


    }

}